package books4africa

import org.springframework.dao.DataIntegrityViolationException
import grails.converters.XML

class UserException extends RuntimeException{
	String message
	String user
}

class UpdateException extends RuntimeException{
	String message
	String user
}

class UserService {
	def userSave(params){
		def user = new User(params)
		def role
		user.enabled = true
		
		if (!user){
			throw new UserException(
				message:"Unable to create user",
				user: user.errors.each{println it}	
			)
		}
		
		switch (user.userType){
			case 'Donor':
				role = SecRole.findByAuthority("ROLE_DONOR")
				break
			
			case 'Teacher':
				role = SecRole.findByAuthority("ROLE_TEACHER")
				break
				
			default:
				role = SecRole.findByAuthority("ROLE_BOTH")
				break
		}
		
		if (!user.authorities.contains(role))
			SecUserSecRole.create user, role, true
		
	}
	
	def userUpdate(params){
		def user = User.get(params.id)
		
		if (!user){
			throw new UserException(
				message:"Can't access the record for ${params.username}",
				user: user.errors.each{println it}
			)
		}
		
		if (params.version){
			def version = params.version.toLong()
			if (user.version > version){
				throw new UpdateException(
					message:"Another user updated this record while you were editing",
					user: user.errors.each{println it}
				)
			}
		}
		
		user.properties = params
		return user
	}
	
	def userDelete(params){
		
		def user = User.get(params.id)
		
		if (!user){
			throw new UserException(
				message:"Can't access the user record for ${user.username}",
				user: user.errors.each{println it}	
			)
		}
		
		if (!user.delete(flush:true)){
			throw new UserException(
				message:"Can't delete user ${user.username}",
				user: user.errors.each{println it}	
			)
		}
		
	}
}

    
